<script lang="ts" setup>
import { onMounted, reactive, getCurrentInstance, ref, onUnmounted, computed, watch } from 'vue'
import { sendServiceData } from '../../common/service'
import { arrToMap, arrToMap2, hasOwnProp, travelTree } from '../../common/utils/normalUtils'
import { queryOrgTreeApi } from '../../common/service/api/deptApi'

const emit = defineEmits(['update:modelValue', 'change'])
const props = defineProps({
  hasOrg: {
    type: Boolean,
    default: true
  },
  modelValue: {
    type: Array,
    default: function() {
      return []
    }
  },
  checkStrictly: {
    type: Boolean,
    default: false
  }
})

const state:any = reactive({
  isLoading: false,
  value: props.modelValue || []
})


const treeOptions = {
  value: 'id',
  label: 'name',
  children: 'children'
}

/**
 * 查询部门列表
 */
const queryRootList = async () => {
  const result = await sendServiceData(queryOrgTreeApi, null, state)
  const list = result || []
  travelTree(list, (item:any) => {
    item.label = item.name
    item.value = item.id
  })
  state.treeData = list
}

const checkHandler = (data:any, checked:boolean) => {
  if (props.checkStrictly && checked && data.children && data.children.length > 0) {
    const arr:any[] = []
    const checkedMap:any = arrToMap2(state.value)
    travelTree(data.children, (item:any) => {
      if (!hasOwnProp(checkedMap, item.id) && !item.disabled)arr.push(item.id)
    })
    state.value.push(...arr)
    emit('update:modelValue', state.value)
  }
}

const changeHandler = () => {
  emit('update:modelValue', state.value)
}

watch(() => props.modelValue, (val:any) => {
  state.value = val || []
})

onMounted(() => {
  state.value = props.modelValue || []
  queryRootList()
})

</script>

<template>
  <el-tree-select v-model="state.value"
                  :data="state.treeData"
                  filterable
                  multiple
                  show-checkbox
                  collapse-tags
                  :props="treeOptions"
                  :check-strictly="checkStrictly"
                  :render-after-expand="false"
                  style="width:100%"
                  class="more-input"
                  @change="changeHandler"
                  @check-change="checkHandler" />
</template>

<style scoped lang="scss">
  .more-input{
    overflow: hidden;
  }
</style>
